import { isIOS } from 'src/utils';
import { scaffoldingKey } from 'src/config/config';

export function copyToClipboard(text: string) {
	const textField = document.createElement('textarea');
	textField.innerText = text;
	textField.style.position = 'fixed';
	document.body.appendChild(textField);
	textField.select();
	const success = document.execCommand('copy');
	document.body.removeChild(textField);

	return success;
}

/**
 * This is the util function to ellipsize for text box
 * if text is longer than expected, change to ... instead
 */
export function ellipsizeTextBox(elem: HTMLElement) {
	const wordArray = elem.innerHTML.split(' ');
	while (elem.scrollHeight > elem.offsetHeight) {
		wordArray.pop();
		elem.innerHTML = `${wordArray.join(' ')} ...`;
	}
}

export function getCookieValue(name: string): string {
	const cookies = document.cookie.match(`(^|;)\\s*${name}\\s*=\\s*([^;]+)`);
	return cookies ? (cookies.pop() as string) : '';
}

export function getStoreValue(name: string) {
	const item = localStorage.getItem(name);
	if (item) {
		return JSON.parse(item);
	} else {
		return null;
	}
}

export function setCookieValue(name: string, value: any, days: number) {
	const date = new Date();
	date.setTime(date.getTime() + days * 24 * 60 * 60 * 1000);
	const expires = `expires=${date.toUTCString()}`;
	document.cookie = `${name}=${JSON.stringify(value)};${expires};path=/`;
}

export function setStoreValue(name: string, value: any) {
	localStorage.setItem(name, JSON.stringify(value));
}

const handleAction = (blob: Blob, fileName: string) => {
	const a = document.createElement('a');
	a.download = fileName;
	a.rel = 'noopener';
	a.style.display = 'none';

	document.body.appendChild(a);
	if (isIOS()) {
		if (blob.size >= 20000000) {
			throw new Error('File exceeds 20MB limit and cannot be saved.');
		}

		const reader = new FileReader();
		reader.readAsDataURL(blob);

		reader.onloadend = (e) => {
			a.href = reader.result as string;
			a.click();
			document.body.removeChild(a);
		};
	} else {
		const url = URL.createObjectURL(blob);
		a.href = url;
		a.click();

		URL.revokeObjectURL(url);
		document.body.removeChild(a);
	}
};

export function saveAs(blob: Blob, fileName: string) {
	if (blob) {
		if (navigator.appVersion.toString().includes('.NET')) {
			navigator.msSaveBlob(blob, fileName);
		} else {
			handleAction(blob, fileName);
		}
	}
}

export function setCulture(value: string) {
	setCookieValue('.AspNetCore.Culture', value === 'zh' ? 'c=zh-CN|uic=zh-CN' : 'c=en-US|uic=en-US', 1);
}

export function getCulture() {
	const culture = getCookieValue('.AspNetCore.Culture');
	if (culture === '') {
		return navigator.language.includes('zh') ? 'zh' : 'en';
	} else if (culture.includes('zh-CN')) {
		return 'zh';
	}
	return 'en';
}

export function getAppInsightKey() {
	const aiKey = getCookieValue('aikey');
	return aiKey ? aiKey : scaffoldingKey;
}
